package com.ruoyi.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.business.domain.DriverDriversLicense;
import com.ruoyi.business.domain.DriverDrivingLicense;
import com.ruoyi.business.domain.SysUserLoginCompany;
import com.ruoyi.business.domain.SysUserLoginDriver;
import com.ruoyi.business.domain.bo.SysUserLoginDriverBo;
import com.ruoyi.business.domain.bo.admin.AdminSysUserLoginDriverBo;
import com.ruoyi.business.domain.vo.SysUserLoginDriverVo;
import com.ruoyi.business.domain.vo.admin.AdminSysUserLoginDriverVo;
import com.ruoyi.business.mapper.DriverDriversLicenseMapper;
import com.ruoyi.business.mapper.DriverDrivingLicenseMapper;
import com.ruoyi.business.mapper.SysUserLoginDriverMapper;
import com.ruoyi.business.mapper.SysUserMapper;
import com.ruoyi.business.service.ISysUserLoginDriverService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * driver 登录账号关联
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserLoginDriverServiceImpl implements ISysUserLoginDriverService {

    private final SysUserLoginDriverMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    private final DriverDriversLicenseMapper driverDriversLicenseMapper;

    private final DriverDrivingLicenseMapper driverDrivingLicenseMapper;

    @Override
    public Boolean insert(SysUserLoginDriver sysUserLoginDriver) {
        return baseMapper.insert(sysUserLoginDriver) > 0;
    }


    /**
     * 查询司机信息
     */
    @Override
    public SysUserLoginDriverVo queryById(Long driverId) {
        return baseMapper.selectVoById(driverId);
    }

    /**
     * 查询司机信息列表
     */
    @Override
    public TableDataInfo<SysUserLoginDriverVo> queryPageList(SysUserLoginDriverBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserLoginDriver> lqw = buildQueryWrapper(bo);
        Page<SysUserLoginDriverVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询司机信息列表
     */
    @Override
    public List<SysUserLoginDriverVo> queryList(SysUserLoginDriverBo bo) {
        LambdaQueryWrapper<SysUserLoginDriver> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserLoginDriver> buildQueryWrapper(SysUserLoginDriverBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserLoginDriver> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTel()), SysUserLoginDriver::getTel, bo.getTel());
        lqw.eq(StringUtils.isNotBlank(bo.getElseParams()), SysUserLoginDriver::getElseParams, bo.getElseParams());
        lqw.eq(bo.getDeptId() != null, SysUserLoginDriver::getDeptId, bo.getDeptId());
        lqw.eq(bo.getUserId() != null, SysUserLoginDriver::getUserId, bo.getUserId());
        lqw.eq(bo.getSubstationId() != null, SysUserLoginDriver::getSubstationId, bo.getSubstationId());
        lqw.eq(bo.getIsDeleted() != null, SysUserLoginDriver::getIsDeleted, bo.getIsDeleted());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), SysUserLoginDriver::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getCardFrontUrl()), SysUserLoginDriver::getCardFrontUrl, bo.getCardFrontUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getCardBackUrl()), SysUserLoginDriver::getCardBackUrl, bo.getCardBackUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getCardId()), SysUserLoginDriver::getCardId, bo.getCardId());
        lqw.eq(bo.getResignationTime() != null, SysUserLoginDriver::getResignationTime, bo.getResignationTime());
        lqw.eq(bo.getEntryTime() != null, SysUserLoginDriver::getEntryTime, bo.getEntryTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUserType()), SysUserLoginDriver::getUserType, bo.getUserType());
        lqw.eq(StringUtils.isNotBlank(bo.getCarType()), SysUserLoginDriver::getCarType, bo.getCarType());
        lqw.eq(bo.getCarLength() != null, SysUserLoginDriver::getCarLength, bo.getCarLength());
        lqw.eq(bo.getCompanyId() != null, SysUserLoginDriver::getCompanyId, bo.getCompanyId());
        lqw.eq(StringUtils.isNotBlank(bo.getOpeningBank()), SysUserLoginDriver::getOpeningBank, bo.getOpeningBank());
        lqw.eq(StringUtils.isNotBlank(bo.getCreditCardNumbers()), SysUserLoginDriver::getCreditCardNumbers, bo.getCreditCardNumbers());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverType()), SysUserLoginDriver::getDriverType, bo.getDriverType());
        lqw.orderByDesc(SysUserLoginDriver::getCreateTime);
        return lqw;
    }

    /**
     * 新增司机信息
     */
    @Override
    public Boolean insertByBo(SysUserLoginDriverBo bo) {
        SysUserLoginDriver add = BeanUtil.toBean(bo, SysUserLoginDriver.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setDriverId(add.getDriverId());
        }
        return flag;
    }

    /**
     * 修改司机信息
     */
    @Override
    public Boolean updateByBo(SysUserLoginDriverBo bo) {
        SysUserLoginDriver update = BeanUtil.toBean(bo, SysUserLoginDriver.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserLoginDriver entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除司机信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    public AdminSysUserLoginDriverVo queryAdminById(Long driverId) {
        SysUserLoginDriverVo sysUserLoginDriverVo = baseMapper.selectVoById(driverId);

        AdminSysUserLoginDriverVo adminSysUserLoginDriverVo = BeanUtil.toBean(sysUserLoginDriverVo, AdminSysUserLoginDriverVo.class);


        //查驾驶证
        DriverDriversLicense driverDriversLicense = driverDriversLicenseMapper.selectOne(new LambdaQueryWrapper<DriverDriversLicense>()
            .eq(DriverDriversLicense::getRelevanceUserId, sysUserLoginDriverVo.getRelevanceUserId())
        );

        if (driverDriversLicense != null) {
            adminSysUserLoginDriverVo.setDriversFrontUrl(driverDriversLicense.getUrl01());
            adminSysUserLoginDriverVo.setDriversBackUrl(driverDriversLicense.getUrl02());
        }

        DriverDrivingLicense driverDrivingLicense = driverDrivingLicenseMapper.selectOne(new LambdaQueryWrapper<DriverDrivingLicense>()
            .eq(DriverDrivingLicense::getRelevanceUserId, sysUserLoginDriverVo.getRelevanceUserId())
        );

        if (driverDrivingLicense != null) {
            adminSysUserLoginDriverVo.setDrivingFrontUrl(driverDrivingLicense.getUrl01());
            adminSysUserLoginDriverVo.setDrivingBackUrl(driverDrivingLicense.getUrl02());
        }

        //查行驶证


        return adminSysUserLoginDriverVo;
    }

    @Override
    public String checkRepeatInfo(AdminSysUserLoginDriverBo bo) {
        SysUserLoginDriver sysUserLoginDriver = baseMapper.selectOne(new LambdaQueryWrapper<SysUserLoginDriver>()
            .ne(bo.getDriverId() != null, SysUserLoginDriver::getDriverId, bo.getDriverId())
            .and((i) -> {
                i.eq(SysUserLoginDriver::getTel, bo.getTel())
                    .or()
                    .eq(SysUserLoginDriver::getCardId, bo.getCardId());

            })
        );

        if (sysUserLoginDriver != null) {
            if (sysUserLoginDriver.getCardId().equals(bo.getCardId())) {
                return "身份证号已经存在，不能重复";
            }

            if (sysUserLoginDriver.getTel().equals(bo.getTel())) {
                return "手机号已经存在，不能重复";
            }
        }

        return "";
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean insertByAdminBo(AdminSysUserLoginDriverBo bo) {
        SysUserLoginDriver sysUserLoginDriver = BeanUtil.toBean(bo, SysUserLoginDriver.class);
        validEntityBeforeSave(sysUserLoginDriver);

        //检查用户是否存在
        SysUser sysUser = sysUserMapper.selectUserByPhonenumber(sysUserLoginDriver.getTel());

        if (sysUser == null) {
            sysUser = new SysUser();
            sysUser.setUserName(sysUserLoginDriver.getTel());
            sysUser.setNickName(sysUserLoginDriver.getRealName());
            sysUser.setPhonenumber(sysUserLoginDriver.getTel());
            sysUser.setStatus(UserStatus.OK.getCode());
            sysUser.setPassword(null);
            sysUser.setUserType(UserType.SYS_USER.getUserType());
            sysUser.setCreateBy(LoginHelper.getUsername());
            sysUser.setCreateTime(DateUtils.getNowDate());
            sysUser.setDelFlag("0");

            //通过身份证号取性别
            if (StringUtils.isNotBlank(sysUserLoginDriver.getCardId()) && sysUserLoginDriver.getCardId().length() == 18) {
                Integer sex = Convert.toInt(sysUserLoginDriver.getCardId().substring(16, 17));
                if (sex != null) {
                    if (sex % 2 == 1) {
                        sysUser.setSex("男");
                    } else {
                        sysUser.setSex("女");
                    }
                }
            }

            int insert = sysUserMapper.insert(sysUser);
            if (insert == 0) {
                log.info("司机用户：{} 注册失败", sysUserLoginDriver.getTel());
                throw new UserException("司机用户注册失败");

            }

            sysUserLoginDriver.setRelevanceUserId(sysUser.getUserId());
        }

        sysUserLoginDriver.setRelevanceUserId(sysUser.getUserId());
        sysUserLoginDriver.setUserType(UserType.SYS_USER.getUserType());
        sysUserLoginDriver.setIsDeleted(0);

        int insert = baseMapper.insert(sysUserLoginDriver);
        if (insert == 0) {
            log.info("司机信息：{} 创建失败", sysUserLoginDriver.getTel());
            throw new ServiceException("司机信息创建失败");
        }

        // 创建驾驶证
        DriverDriversLicense driverDriversLicense = new DriverDriversLicense();
        driverDriversLicense.setRelevanceUserId(sysUserLoginDriver.getRelevanceUserId());
        driverDriversLicense.setUrl01(bo.getDriversFrontUrl());
        driverDriversLicense.setUrl02(bo.getDriversBackUrl());
        driverDriversLicense.setIsDeleted(0);

        int driversInsert = driverDriversLicenseMapper.insert(driverDriversLicense);
        if (driversInsert == 0) {
            log.info("驾驶证创建失败：{} 创建失败", sysUserLoginDriver.getTel());
            throw new ServiceException("驾驶证创建失败");
        }

        // 创建行驶证
        DriverDrivingLicense driverDrivingLicense = new DriverDrivingLicense();
        driverDrivingLicense.setRelevanceUserId(sysUserLoginDriver.getRelevanceUserId());
        driverDrivingLicense.setUrl01(bo.getDrivingFrontUrl());
        driverDrivingLicense.setUrl02(bo.getDrivingBackUrl());
        driverDrivingLicense.setIsDeleted(0);

        int drivingInsert = driverDrivingLicenseMapper.insert(driverDrivingLicense);
        if (drivingInsert == 0) {
            log.info("行驶证创建失败：{} 创建失败", sysUserLoginDriver.getTel());
            throw new ServiceException("行驶证创建失败");
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean updateByAdminBo(AdminSysUserLoginDriverBo bo) {
        SysUserLoginDriver sysUserLoginDriver = BeanUtil.toBean(bo, SysUserLoginDriver.class);
        validEntityBeforeSave(sysUserLoginDriver);

        int update = baseMapper.updateById(sysUserLoginDriver);
        if (update == 0) {
            throw new ServiceException("司机修改失败");
        }

        // 驾驶证 先删后增
        driverDriversLicenseMapper.delete(new LambdaQueryWrapper<DriverDriversLicense>()
            .eq(DriverDriversLicense::getRelevanceUserId, sysUserLoginDriver.getRelevanceUserId())
        );

        // 创建驾照
        DriverDriversLicense driverDriversLicense = new DriverDriversLicense();
        driverDriversLicense.setRelevanceUserId(sysUserLoginDriver.getRelevanceUserId());
        driverDriversLicense.setUrl01(bo.getDriversFrontUrl());
        driverDriversLicense.setUrl02(bo.getDriversBackUrl());
        driverDriversLicense.setIsDeleted(0);

        int driversInsert = driverDriversLicenseMapper.insert(driverDriversLicense);
        if (driversInsert == 0) {
            log.info("驾驶证创建失败：{} 创建失败", sysUserLoginDriver.getTel());
            throw new ServiceException("驾驶证创建失败");
        }

        // 行驶证 先删后增
        driverDrivingLicenseMapper.delete(new LambdaQueryWrapper<DriverDrivingLicense>()
            .eq(DriverDrivingLicense::getRelevanceUserId, sysUserLoginDriver.getRelevanceUserId())
        );
        // 创建行驶证
        DriverDrivingLicense driverDrivingLicense = new DriverDrivingLicense();
        driverDrivingLicense.setRelevanceUserId(sysUserLoginDriver.getRelevanceUserId());
        driverDrivingLicense.setUrl01(bo.getDrivingFrontUrl());
        driverDrivingLicense.setUrl02(bo.getDrivingBackUrl());
        driverDrivingLicense.setIsDeleted(0);

        int drivingInsert = driverDrivingLicenseMapper.insert(driverDrivingLicense);
        if (drivingInsert == 0) {
            log.info("行驶证创建失败：{} 创建失败", sysUserLoginDriver.getTel());
            throw new ServiceException("行驶证创建失败");
        }


        return true;
    }
}
